<template>
  <div>
    <el-card>
      <div slot="header" class="clearfix">
        <span>条件搜索</span>
        <div class="base-el-float-right">
          <el-button-group>
            <el-button type="primary" icon="el-icon-refresh" @click="resetForm">重置</el-button>
            <el-button type="primary" icon="el-icon-search" @click="submitForm">搜索</el-button>
          </el-button-group>
        </div>
      </div>
      <el-form ref="ruleForm" :inline="true" :model="formInline">
        <el-form-item label="订单状态:">
          <el-select v-model="formInline.status">
            <el-option :value="0" label="已取消" />
            <el-option :value="1" label="已提交" />
            <el-option :value="2" label="已付款" />
            <el-option :value="3" label="配送中" />
            <el-option :value="4" label="已完成" />
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 订单列表 -->
    <el-card class="base-el-card-bottom">
      <div slot="header" class="clearfix">
        <span>订单列表</span>
        <el-button class="base-el-float-right" type="primary" icon="el-icon-refresh" @click="submitForm">刷新</el-button>
      </div>
      <PaginationTable
        :table-data="tableData"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @handleChange="handleTableSizeChange"
      >
        <el-table-column label="序号" type="index" width="50" />
        <el-table-column label="客户信息" width="250">
          <template slot-scope="scope">
            <p>姓名：<b>{{ scope.row.name }}</b></p>
            <p>电话：<b>{{ scope.row.phone }}</b></p>
            <p>地址：<b>{{ scope.row.area }}</b></p>
            <p>详细地址：{{ scope.row.detailedAddress }}</p>
          </template>
        </el-table-column>
        <el-table-column label="商品信息">
          <template slot-scope="scope">
            <p v-for="(item,index) of scope.row.productList" :key="index">
              <el-image :src="item.image" :preview-src-list="[item.image]" /><br>
              <span>产品标题：<b>{{ item.title }}</b></span><br>
              <span>sku标题：<b>{{ item.skuTitle }}</b></span><br>
              <span>数量：<b>{{ item.count }}</b></span><br>
              <span style="color: red">价格：￥{{ (item.count * item.price / 100).toFixed(2) }}</span>
            </p>
          </template>
        </el-table-column>
        <el-table-column label="订单信息" width="230">
          <template slot-scope="scope">
            <p>备注：{{ scope.row.remark }}</p>
            <p>订单编号：<br><el-link type="primary">{{ scope.row.orderNo }}</el-link></p>
            <p style="color: red">
              订单价格：￥{{ (scope.row.price / 100).toFixed(2) }}
              <span v-if="scope.row.discount < 100">（{{ scope.row.discount }}折）</span>
            </p>
            <p>订单状态：<b :style="{'font-size': '20px', color: ['#F56C6C', '#409EFF', '#67C23A', '#409EFF', '#67C23A'][scope.row.status]}">{{ scope.row.status | orderStatusFilter }}</b></p>
          </template>
        </el-table-column>
        <el-table-column label="时间信息" width="230">
          <template slot-scope="scope">
            <span>提交时间：{{ scope.row.createTime | timeFormatFilter }}<br></span>
            <span v-if="scope.row.cancelTime">取消时间：{{ scope.row.cancelTime | timeFormatFilter }}<br></span>
            <span v-if="scope.row.payTime">付款时间：{{ scope.row.payTime | timeFormatFilter }}<br></span>
            <span v-if="scope.row.deliveryTime">配送时间：{{ scope.row.deliveryTime | timeFormatFilter }}<br></span>
            <span v-if="scope.row.finishTime">完成时间：{{ scope.row.finishTime | timeFormatFilter }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-link v-if="!scope.row.payTime" type="primary" @click="handleOrderStatusEdit({ orderData: scope.row, status: 2})">设置为已付款<br></el-link>
            <el-link v-if="!scope.row.deliveryTime" type="primary" @click="handleOrderStatusEdit({ orderData: scope.row, status: 3})">设置为配送中<br></el-link>
            <el-link v-if="!scope.row.finishTime" type="primary" @click="handleOrderStatusEdit({ orderData: scope.row, status: 4})">设置为已完成<br></el-link>
          </template>
        </el-table-column>
      </PaginationTable>
    </el-card>
  </div>
</template>
<script>

import PaginationTable from '@/components/PaginationTable'
import { queryByCondition, updateById } from '@/api/commoncrud'
import OrderStatus from '@/const/OrderStatus'
const defaultFormInline = {
  status: ''
}
export default {
  name: 'User',
  components: { PaginationTable },
  filters: {
    orderStatusFilter(value) {
      return OrderStatus[value]
    }
  },
  data() {
    return {
      area: {},
      tableData: [],
      total: 0,
      pageSize: 10,
      currentPage: 1,

      formInline: {
        ...defaultFormInline
      }
    }
  },
  async created() {
    this.area = JSON.parse(window.localStorage.getItem('defaultArea'))
    await this.fetchData()
  },
  methods: {
    async fetchData() {
      const query = { areaId: this.area._id, sort: { createTime: -1 }}
      Object.keys(this.formInline).forEach(key => {
        if (this.formInline[key] || this.formInline[key] === 0) { query[key] = this.formInline[key] }
      })
      const res = await queryByCondition('order', (this.currentPage - 1) * this.pageSize, this.pageSize, query)
      this.tableData = res.data.documentList
      this.total = res.data.documentCount
    },
    async handleOrderStatusEdit({ orderData, status }) {
      const data = { status }
      const time = Math.round(new Date().getTime() / 1000)
      let title = ''
      if (status === 2) {
        title = '确认修改为已付款？'
        data.payTime = time
      }
      if (status === 3) {
        title = '确认修改为配送中？'
        data.deliveryTime = time
      }
      if (status === 4) {
        title = `确认修改为已完成？用户将获得${orderData.price / 100}个积分`
        data.finishTime = time
      }
      this.$alert(title, '消息提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showCancelButton: true,
        callback: async action => {
          if (action === 'confirm') {
            await updateById('order', orderData._id, data)
            if (status === 4) {
              await updateById('userbase', orderData.userId, { $inc: { score: orderData.price / 100 }})
            }
            this.$message.success('更新成功!')
            await this.fetchData()
          }
        }
      })
    },
    // 表格数据
    async resetForm() {
      this.formInline = {
        ...defaultFormInline
      }
      this.currentPage = 1
      await this.fetchData()
    },
    async handleTableSizeChange({ currentPage, pageSize }) {
      this.pageSize = pageSize
      this.currentPage = currentPage
      await this.fetchData()
    },
    async submitForm() {
      this.currentPage = 1
      await this.fetchData()
    }
  }
}
</script>

<style scoped>
</style>
